package com.Humanities.ucenter.service.impl;

import com.Humanities.ucenter.feignclient.CheckCodeClient;
import com.Humanities.ucenter.mapper.XcUserMapper;
import com.Humanities.ucenter.mapper.XcUserRoleMapper;
import com.Humanities.ucenter.model.dto.FindPasswordDTO;
import com.Humanities.ucenter.model.dto.RegisterDTO;
import com.Humanities.ucenter.model.po.XcUser;
import com.Humanities.ucenter.model.po.XcUserRole;
import com.Humanities.ucenter.service.AccountPasswordService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class AccountPasswordServiceImpl implements AccountPasswordService {
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    CheckCodeClient checkCodeClient;
    @Autowired
    AccountPasswordService accountPasswordService;
    @Autowired
    XcUserRoleMapper xcUserRoleMapper;
    @Override
    public RestResponse findPassword(FindPasswordDTO findPasswordDTO) {
        //判断验证码是否正确
        String checkCode = findPasswordDTO.getCheckcode();
        String checkCodeKey = findPasswordDTO.getCheckcodekey();
        if (checkCode == null || checkCodeKey == null) {
            throw new RuntimeException("验证码不能为空");
        }
        //调用验证码服务校验验证码
        Boolean verify = checkCodeClient.verify(checkCodeKey, checkCode);
        if (verify == null || !verify) {
            throw new RuntimeException("验证码错误");
        }
        //判断邮箱和手机号的用户是否存在
        String cellphone = findPasswordDTO.getCellphone();
        String email = findPasswordDTO.getEmail();
        XcUser user = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getCellphone, cellphone).eq(XcUser::getEmail, email));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        //判断两次密码是否一致
        String password = findPasswordDTO.getPassword();
        String passwordConfirm = findPasswordDTO.getConfirmpwd();
        if (!password.equals(passwordConfirm)) {
            throw new RuntimeException("两次密码不一致");
        }

        //修改用户的密码为新密码(加密)
        String encode = this.encode(password);
        user.setPassword(encode);
        xcUserMapper.updateById(user);

      return RestResponse.success("密码忘记成功");
    }

    @Override
    public RestResponse register(RegisterDTO registerDTO) {
        //检验验证码是否正确
        String checkCode = registerDTO.getCheckcode();
        String checkCodeKey = registerDTO.getCheckcodekey();
        if (checkCode == null || checkCodeKey == null) {
            throw new RuntimeException("验证码不能为空");
        }
        //调用验证码服务校验验证码
        Boolean verify = checkCodeClient.verify(checkCodeKey, checkCode);
        if (verify == null || !verify) {
            throw new RuntimeException("验证码错误");
        }
        //校验用户是否存在
        String username = registerDTO.getUsername();
        String cellphone = registerDTO.getCellphone();
        String email = registerDTO.getEmail();
        XcUser user = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername,username).eq(XcUser::getCellphone, cellphone)
                .eq(XcUser::getEmail, email));
        if (null != user){
            throw new XueChengPlusException("该用户已存在，请勿重复注册！");
        }

        //向用户表插入数据，设置角色为学生
        accountPasswordService.initUserDBData(registerDTO);
        return RestResponse.success("注册成功！");


    }

    @Override
    @Transactional
    public void initUserDBData(RegisterDTO registerDTO) {
        XcUser xcUser = new XcUser();
        xcUser.setId(UUID.randomUUID().toString());
        //记录从微信得到的昵称
        BeanUtils.copyProperties(registerDTO,xcUser);
        xcUser.setPassword(encode(registerDTO.getPassword()));
        xcUser.setUtype("101001");//学生类型
        xcUser.setStatus("1");//用户状态
        xcUser.setCreateTime(LocalDateTime.now());
        xcUser.setUsername(registerDTO.getUsername());
        xcUser.setName(registerDTO.getNickname());
        xcUserMapper.insert(xcUser);

        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setId(UUID.randomUUID().toString());
        xcUserRole.setUserId(xcUser.getId());
        xcUserRole.setRoleId("17");
        xcUserRole.setCreateTime(LocalDateTime.now());
        xcUserRoleMapper.insert(xcUserRole);

    }

    private String encode(String password) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder.encode(password);
    }



}
